package com.feige.helper;

import com.feige.pojo.Permission;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 根据权限数据构建菜单数据
 * @author
 * @since
 */
public class PermissionHelper {
    /**
     *递归建菜单
     * @param permissions
     * @return
     */
    public static List<Permission> build(List<Permission> permissions){
        List<Permission> permissionList = new ArrayList<>();
        for (Permission permission : permissions) {
            if (permission.getPid() == 0) {
                permissionList.add(findChildren(permission,permissions));
            }
        }
        return permissionList;
    }


    /**
     * 查找子节点
     * @param rootNode
     * @param permissions
     * @return
     */
    private static Permission findChildren(Permission rootNode,List<Permission> permissions){
        rootNode.setChildren(new ArrayList<>());
        for (Permission permission : permissions) {
            if (rootNode.getId().equals(permission.getPid())) {
                if (rootNode.getChildren() == null){
                    rootNode.setChildren(new ArrayList<>());
                }
                rootNode.getChildren().add(findChildren(permission,permissions));
            }
        }
        return rootNode;
    }
}
